<style>
* {
    margin: 0px;
    padding: 0px;
}

.col-marleft {
    display: flex;
    justify-content: space-around;
}

.head_search {
    margin-bottom: 10px;
}
</style>
<template>
    <!-- 头部搜索 -->
    <div class="head_search">
        <el-row>
            <el-col :span="5">
                <el-input v-model="search" placeholder="请输入专家名称" />
            </el-col>
            <el-col :span="10">
                <!-- 搜索 -->
                <el-button type="primary" plain style="margin-left: 10px;" @click="getDataByName">
                    <el-icon>
                        <Search />
                    </el-icon>搜索
                </el-button>
                <!-- 打开添加弹窗 -->
                <el-button type="info" @click="dialogFormVisible = true" plain>
                    <el-icon>
                        <Plus />
                    </el-icon>添加
                </el-button>
                <!-- 批量删除 -->
                <el-button type="danger" @click="handleDelete(0, 0)" plain>
                    <el-icon>
                        <Delete />
                    </el-icon>批量删除
                </el-button>
            </el-col>
        </el-row>
    </div>
    <!-- 表格 -->
    <!-- 设置表格中的语言配置为中文 -->
    <el-config-provider :locale="zhCn">
        <el-table :data="tableData" row-key="id" style="width: 100%;" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="专家名称" prop="doctorName" width="150" />
            <el-table-column label="职称" prop="title" />
            <el-table-column label="医生代码" prop="doctorCode" width="100" />
            <el-table-column label="排序" prop="orderNum" width="100" />
            <el-table-column label="头像" prop="images">
                <template #default="scope">
                    <el-image style="width: 70px; height: 70px" :src="scope.row.images" />
                </template>
            </el-table-column>
            <el-table-column label="科室" prop="deptName" />
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button size="small" plain type="success" @click="handleAdd(scope.$index, scope.row)"
                        :icon="Plus"><el-icon>
                            <CirclePlus />
                        </el-icon></el-button>
                    <el-button size="small" type="primary" plain :icon="Edit"
                        @click="handleEdit(scope.$index, scope.row)" />
                    <el-button v-if="scope.row.parentId !== 0" size="small" type="danger" plain :icon="Delete"
                        @click="handleDelete(scope.$index, scope.row)" />
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="demo-pagination-block" style="margin-top: 10px;">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50, 100]" :small="small" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </el-config-provider>
    <!-- 添加/编辑Form -->
    <el-dialog v-model="dialogFormVisible" title="添加专家" :before-close="handleClose">
        <el-form :model="form" :label-position="labelPosition" class="demo-form-inline">

            <!-- 专家名称/职称-->
            <el-row class="col-marleft">
                <el-col :span="11">
                    <el-form-item label="专家名称">
                        <el-input v-model="form.doctorName" placeholder="请输入专家名称" autocomplete="off" />
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="职称">
                        <el-input v-model="form.title" placeholder="请输入职称" autocomplete="off" />

                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 医生代码/擅长-->
            <el-row class="col-marleft">
                <el-col :span="11">
                    <el-form-item label="医生代码">
                        <el-input v-model="form.doctorCode" placeholder="请输入医生代码" autocomplete="off" />
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="擅长">
                        <el-input v-model="form.skilled" placeholder="请输入擅长" autocomplete="off" />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 排序/科室-->
            <el-row class="col-marleft">
                <el-col :span="11">
                    <el-form-item label="排序">
                        <el-input-number v-model="form.orderNum" style="width: 100%;" class="mx-4" :min="1"
                            controls-position="right" />
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="科室">
                        <el-select v-model="form.deptid" class="m-2" placeholder="请选择科室" style="width: 100%">
                            <el-option v-for="item in deptList" :key="item.id" :label="item.deptName" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 头像-->
            <el-row class="col-marleft">
                <el-col :span="23">
                    <el-form-item label="头像">
                        <el-upload action="#" list-type="picture-card" :auto-upload="false" @change="changehaner">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            <template #file="{ file }" v-if="showActions">
                                <div>
                                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                                    <span class="el-upload-list__item-actions">
                                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                            <el-icon><zoom-in /></el-icon>
                                        </span>
                                        <span v-if="!disableds" class="el-upload-list__item-delete"
                                            @click="handleDownload(file)">
                                            <el-icon>
                                                <Download />
                                            </el-icon>
                                        </span>
                                        <span v-if="!disableds" class="el-upload-list__item-delete"
                                            @click="handleRemove(file)">
                                            <el-icon>
                                                <Delete />
                                            </el-icon>
                                        </span>
                                    </span>
                                </div>
                            </template>
                        </el-upload>

                        <el-dialog v-model="dialogVisible">
                            <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: 100%;" />
                        </el-dialog>

                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 简介-->
            <el-row class="col-marleft">
                <el-col :span="23">
                    <el-form-item label="简介">
                        <el-input v-model="form.introduction" :rows="2" type="textarea" placeholder="请输入简介" />
                    </el-form-item>
                </el-col>
            </el-row>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="btnSave">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { computed, onMounted, ref, reactive, watch } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox, ElConfigProvider } from 'element-plus'
// 引入中文包
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
//引入七牛云包
import * as qiniu from 'qiniu-js';
import { Delete, Edit, Search, Share, Upload, Add } from '@element-plus/icons-vue'

//设置添加部门表单的input前文字
const labelPosition = ref('top');

//存储选中的数据的id集合
const idArr = ref([]);

//弹出窗状态
var dialogFormVisible = ref(false)


//获取表格多选按钮选中后的数据id集合
const handleSelectionChange = (val) => {
    idArr.value = val.map(item => item.id); // 获取选中行的id组成的数组，假设id是每一行的一个
}

//存储服务器返回的所有数据
var tableData = ref([]);

//搜索框数据
var search = ref('');
//搜索
function getDataByName() {
    bindData(pageSize.value, 1, search.value);
}

//页面渲染后加载
onMounted(() => {
    bindData(pageSize.value, 1, search.value);
});


//编辑
var handleEdit = (index, row) => {
    Object.assign(form, row);
    dialogFormVisible.value = true;
}

//删除
var handleDelete = (index, row) => {
    var id;//删除数据的主键
    ElMessageBox.confirm(
        '确定要删除吗?',
        'Warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        id = row.id > 0 ? row.id : idArr.value.join(',');
        axios.delete(`/api/business/Doctor/${id}`).then(function (res) {
            // console.log(res);
            //返回格式：{code: 110, msg: "存在下级部门，不允许删除"}
            if (res.data.code == 200) {
                ElMessage({
                    type: 'success',
                    message: "删除成功"
                })
                bindData(pageSize.value, 1, search.value);
            } else {
                ElMessage({
                    type: 'warning',
                    message: "删除失败" + res.data.msg
                })
            }

        }).catch(() => {
            ElMessage({
                type: 'warning',
                message: "删除失败!"
            })
        })

    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '用户取消操作',
        })
    })
}



//分页
const currentPage = ref(1)//当前页数
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const pageSize = ref(5)//每页条数
const total = ref(0)//总数据量

//切换每页条数
const handleSizeChange = (val) => {
    bindData(val, currentPage.value, search.value);
}

//切换页数
const handleCurrentChange = (val) => {
    bindData(pageSize.value, val, search.value);
}

//存储科室信息
var deptList = ref([]);


//查询绑定数据
function bindData(page, pageNum, strName) {
    axios.get(`/api/business/Doctor/list?PageNum=${pageNum}&PageSize=${page}&TotalNum=16&TotalPageNum=0&DoctorName=${strName}`).then(function (res) {
        currentPage.value = res.data.data.pageIndex;
        total.value = res.data.data.totalCount;
        tableData.value = res.data.data.result;

        //获取科室信息
        axios.get(`/api/business/Dept/alllist`).then((res) => {
            var arr = res.data.data;
            deptList.value = arr;
            for (let i = 0; i < tableData.value.length; i++) {
                arr.forEach((item) => {
                    if (tableData.value[i].deptid == item.id) {
                        console.log(tableData.value[i].deptid, item.id);
                        tableData.value[i]["deptName"] = item.deptName;
                    }
                })
            }
            console.log(tableData.value);
        })
    }).catch(() => {
        ElMessage({
            type: 'warning',
            message: "网络异常!"
        })
    });
}



//存储保存添加/编辑时的数据
var form = reactive({
    id: 0,
    doctorName: "",//医生名称
    introduction: "",//简介
    title: "",//职称
    skilled: "",//擅长
    images: "",//头像
    deptid: 0,//科室id
    orderNum: 0,//排序字段
    doctorCode: "",//医生代码
    deptName: ""//科室名称
});

//保存
function btnSave() {
    axios({
        url: '/api/business/Doctor',
        method: form.id == 0 ? 'post' : 'put',
        data: form
    }).then((res) => {
        var str = form.id == 0 ? '添加' : '编辑'
        if (res.data.code == 200) {
            ElMessage({
                message: str + '成功',
                type: 'success',
            });
            clearForm();
            bindData(pageSize.value, 1, search.value);
        } else {
            ElMessage({
                message: str + '失败',
                type: 'warning',
            })
        }
    })
}

//模态框关闭
const handleClose = () => {
    clearForm();
}

//清理form表单存留数据
function clearForm() {
    dialogFormVisible.value = false;
    var info = {
        id: 0,
        doctorName: "",//医生名称
        introduction: "",//简介
        title: "",//职称
        skilled: "",//擅长
        images: "",//头像
        deptid: 0,//科室id
        orderNum: 0,//排序字段
        doctorCode: "",//医生代码
        deptName: ""//科室名称
    }
    Object.assign(form, info)
}

function changehaner(e) {
    const file = e.raw;
    const key = getNowDate() + file.name;
    //从服务器拿的并存在本地data里,过期需要重新生成
    axios.get('http://8.130.174.200:8085/api/UploadImgToQiNiuYun/getToken').then(res => {
        const token = res.data.token;
        const putExtra = {
            fname: '',
            params: {},
            mimeType: ['image/png', 'image/jpeg', 'image/jpg'],//要求上传的格式
        };

        const config = {
            useCdnDomain: true, //使用cdn加速
        };
        const observable = qiniu.upload(file, key, token, putExtra, config);

        observable.subscribe({
            next: (result) => {
                // 主要用来展示进度
                console.warn(result);
            },
            error: (error) => {
                console.log(error)
            },
            complete: (res) => {
                // 生成图片路径
                const domain = 'http://s711x59qz.hd-bkt.clouddn.com'; // 替换为您的七牛云域名
                const imageURL = `${domain}/${res.key}`;
                console.log(imageURL);
                form.images = imageURL;
            },
        });
    })
}
//获取当前时间，用于拼接上传图片的名称
function getNowDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = ('0' + (now.getMonth() + 1)).slice(-2);
    const day = ('0' + now.getDate()).slice(-2);
    const hours = ('0' + now.getHours()).slice(-2);
    const minutes = ('0' + now.getMinutes()).slice(-2);
    const seconds = ('0' + now.getSeconds()).slice(-2);
    return `${year}${month}${day}${hours}${minutes}${seconds}`;
}
</script>